<template>
  <div class="container">
    <!-- 查询区域 -->
    <el-row style="height:100%;">
      <el-col :span="4" style="height:100%;">
        <div class="tree-container" style="padding:10px;margin-right:20px;border:solid 1px #DCDFE6;height:100%;overflow:auto">
          <h3>所属供应商</h3>
          <el-input placeholder="输入供应商名称进行过滤"
                    v-model="treeFilter"
                    class="tree-filter"
                    style="margin:10px;width:80%"/>
          <el-tree
            ref="tree"
            highlight-current
            default-expand-all
            node-key="id"
            :expand-on-click-node="false"
            :data="treeData"
            :props="defaultProps"
            :filter-node-method="handleTreeFilter"
            @node-click="handleTreeNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20">
        <el-row :gutter="18">
          <el-header style="text-align: right; border-bottom: black ; margin-right: 10px">
            <el-form
              class="input-form" label-position="right" label-width="20px" ref="editForm"
              :model="query"
            >
              <el-col :span="5">
                <el-form-item label="起" prop="beginDate">
                  <el-date-picker  v-model="query.beginDate" type="date" :format="dates.defaultDatePattern"  :picker-options="dates.pickerOptions.date"/>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="终" prop="endDate">
                  <el-date-picker  v-model="query.endDate" type="date" :format="dates.defaultDatePattern"  :picker-options="dates.pickerOptions.date"/>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="" prop="deptId" >
                  <el-select v-model="query.deptId" filterable :disabled="flagAllData" >
                    <el-option
                      v-for="item in deptIds"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="" prop="warehouseId">
                  <el-select v-model="query.warehouseId" filterable >
                    <el-option
                      v-for="item in warehouses"
                      :key="item.id"
                      :label="item.warehouseName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-button type="primary" @click="searchResult">确认</el-button>
            </el-form>
          </el-header>
          <hr>
        </el-row>
        <el-collapse v-model="activeNames">
          <el-collapse-item title="汇总数据" name="2">
            <el-form
              class="input-form" label-position="right" label-width="110px" ref="editForm"
              :model="form"
            >
              <el-row :gutter="18" style="margin-top: 20px">

                <el-col :span="4">
                  <el-form-item label="期初数量" prop="qtyBeginSum">
                    <el-input v-model="form.qtyBeginSum" disabled placeholder="0"/>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="期末数量" prop="qtyEndSum">
                    <el-input v-model="form.qtyEndSum" disabled placeholder="0"/>
                  </el-form-item>
                </el-col>

                <el-col :span="4">
                  <el-form-item label="入库数量" prop="qtyInSum">
                    <el-input v-model="form.qtyInSum" disabled placeholder="0"/>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="出库数量" prop="qtyOutSum">
                    <el-input v-model="form.qtyOutSum" disabled placeholder="0"/>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="消耗数量" prop="qtyConsumeOutSum">
                    <el-input v-model="form.qtyConsumeOutSum" disabled placeholder="0"/>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="计费数量" prop="qtyChargingSum">
                    <el-input v-model="form.qtyChargingSum" disabled placeholder="0"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="18">
                <el-col :span="4">
                  <el-form-item label="期初金额" prop="amountBeginSum">
                    <el-input v-model="form.amountBeginSum" disabled placeholder="0"/>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="期末金额" prop="amountEndSum">
                    <el-input v-model="form.amountEndSum" disabled placeholder="0"/>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="入库金额" prop="amountInSum">
                    <el-input v-model="form.amountInSum" disabled placeholder="0"/>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="出库金额" prop="amountOutSum">
                    <el-input v-model="form.amountOutSum" disabled placeholder="0"/>
                  </el-form-item>
                </el-col>


                <el-col :span="4">
                  <el-form-item label="消耗金额" prop="amountConsumeOutSum">
                    <el-input v-model="form.amountConsumeOutSum" disabled placeholder="0"/>
                  </el-form-item>
                </el-col>

                <el-col :span="4">
                  <el-form-item label="计费金额" prop="amountChargingSum">
                    <el-input v-model="form.amountChargingSum" disabled placeholder="0"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-collapse-item>
        </el-collapse>
        <div v-show="showTabs" style="height:700px;overflow:visible;">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="品规日清" name="specList">
              <data-view
                ref="dataView"
                propViewKey="dept_monthly_balance_item"
                :propShowToolBar="true"
                :propInitData="selectedTreeNode"
              />
            </el-tab-pane>
            <el-tab-pane label="收费日清" name="chargeList">
              <data-view
                ref="dv"
                propViewKey="his_monthly_balance_item"
                :propShowToolBar="true"
                :propInitData="selectedTreeNode"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>

export default {
  name: 'dailybalance',
  data() {
    return {
      flagAllData: true,
      activeNames: ['1', '2', '12'],
      input: '',
      treeData: [],
      activeName: '',
      showTabs: true,
      treeFilter: '',
      selectedTreeNode: {},
      treeEntry: '/base/supplier/all',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      nowDate: '',
      form: {},
      query: {},
      deptIds: [],
      warehouses: [],
      loading: false,
      tableData: [],
      tableCustom: {
        storage: true
      },
      tableToolbar: {
        custom: true,
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
    }
  },
  created() {
    this.getDepts()
    this.setDefaultValue()
  },
  components: {
  },
  watch: {
    treeFilter(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    handleClick(tab, event) {
      if (tab.name == 'specList') {
        let wrapper = this.getChildViewQueryWrapper()
        this.$refs.dataView.setQueryWrapper(wrapper)
      }
      if (tab.name == 'chargeList') {
        let wrapper = this.getChildViewQueryWrapper()
        this.$refs.dv.setQueryWrapper(wrapper)
      }
    },
    async loadTree() {
      await this.$ajax.get(this.treeEntry, {}).then(response => {
        if (response.code == 0) {
          response.data.forEach(o => {
            o.parentId = 0
          })
          this.treeDataLoad(response.data)
        } else {
          this.utilMessage.error(response.msg)
        }
      })
    },
    treeDataLoad(data) {
      this.treeData = global.utils.convertToTree(data, {
        rootNode: {id: '0', parentId: '-1', name: '所有供应商' },
        keyFieldName: 'id',
        parentFieldName: 'parentId',
        labelFieldName: 'name'
      }) // {CHECK_HERE}
      if (!this.selectedTreeNode.id) {
        this.selectedTreeNode = this.treeData[0]
      }
      this.$refs.tree.setCurrentKey(this.selectedTreeNode.id)
    },
    handleTreeNodeClick(data) {
      let wrapper
      let balanceDateStart = new Date(this.query.beginDate).format(this.dates.defaultDatePattern)
      let balanceDateEnd = new Date(this.query.endDate).format(this.dates.defaultDatePattern)
      if (this.query.warehouseId == 0) {
        wrapper = data.id == 0 ? this.$newWrapper()
          .eq('deptMonthlyBalanceId', this.form.id)
          : this.$newWrapper().eq('supplier_id', data.id)
            .eq('deptMonthlyBalanceId', this.form.id)
      } else {
        wrapper = data.id == 0 ? this.$newWrapper()
          .eq('deptMonthlyBalanceId', this.form.id)
          : this.$newWrapper().eq('supplier_id', data.id)
            .eq('deptMonthlyBalanceId', this.form.id)
      }

      this.selectedTreeNode = data

      this.$refs.dataView.setQueryWrapper(wrapper)
      this.$refs.dv.setQueryWrapper(wrapper)

      setTimeout(() => {
        if (this.activeName == 'specList') {
          let childRow = this.$refs.dataView.rows
          this.getChildViewSum(childRow)
        }
        if (this.activeName == 'chargeList') {
          let childRow = this.$refs.dv.rows
          this.getChildViewSum(childRow)
        }
      }, 500)
    },

    getChildViewSum(childRow) {
      if (!childRow) {
        return
      }
      this.form.amountBeginSum = childRow.map(o => o.amountBegin).reduce((acc, cur) => { return acc + cur }, 0)
      this.form.qtyBeginSum = childRow.map(o => o.qtyBegin).reduce((acc, cur) => { return acc + cur }, 0)
      this.form.amountOutSum = childRow.map(o => o.amountOut).reduce((acc, cur) => { return acc + cur }, 0)
      this.form.qtyOutSum = childRow.map(o => o.qtyOut).reduce((acc, cur) => { return acc + cur }, 0)
      this.form.amountConsumeOutSum = childRow.map(o => o.amountConsumeOut).reduce((acc, cur) => { return acc + cur }, 0)
      this.form.qtyConsumeOutSum = childRow.map(o => o.qtyConsumeOut).reduce((acc, cur) => { return acc + cur }, 0)
      this.form.qtyEndSum = childRow.map(o => o.qtyEnd).reduce((acc, cur) => { return acc + cur }, 0)
      this.form.amountEndSum = childRow.map(o => o.amountEnd).reduce((acc, cur) => { return acc + cur }, 0)
      this.form.qtyInSum = childRow.map(o => o.qtyIn).reduce((acc, cur) => { return acc + cur }, 0)
      this.form.amountInSum = childRow.map(o => o.amountIn).reduce((acc, cur) => { return acc + cur }, 0)
      this.form.amountChargingSum = childRow.map(o => o.amountCharging).reduce((acc, cur) => { return acc + cur }, 0)
      this.form.qtyChargingSum = childRow.map(o => o.qtyCharging).reduce((acc, cur) => { return acc + cur }, 0)
    },
    getChildViewQueryWrapper() {
      if (this.query.warehouseId == 0) {
        return this.$newWrapper().eq('deptMonthlyBalanceId', this.form.id)
      } else {
        return this.$newWrapper().eq('deptMonthlyBalanceId', this.form.id)
      }
    },
    handleTreeFilter(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleAfterSave(status, data) {
      this.loadTree()
    },
    handleAfterDelete() {
      this.loadTree()
    },
    getDepts() {
      let that = this
      that.$ajax.get('/base/dept/list', {}).then((response) => {
        that.deptIds = response.data
      })
    },
    setDefaultValue() {
      this.$ajax.get('/base/user_warehouse/getByCurrentUser').then(res => {
        if (res.code == 0) {
          this.warehouses = res.data || []
          if (this.utils.getCurrentUser().deptDataAll) {
            this.flagAllData = true
            let all = {
              flagDefault: null,
              id: '0',
              userCode: null,
              userId: null,
              userName: null,
              warehouseCode: null,
              warehouseId: null,
              applyWarehouseId: null,
              warehouseName: '全部库存地',
              applyWarehouseName: null
            }
            this.warehouses.push(all)
          }
        }
      })
      let date = new Date()
      date.setMonth(date.getMonth() - 1)
      this.$set(this.query, 'deptId', this.utils.getCurrentUser().deptId)
      this.$set(this.query, 'warehouseId', this.utils.getCurrentWarehouse().id)
      this.$set(this.query, 'beginDate', this.dates.getFirstDayOfMonth(date).format(this.dates.defaultDatePattern))
      this.$set(this.query, 'endDate', this.dates.getLastDayOfMonth(date).format(this.dates.defaultDatePattern))
    },
    async treeSetDataLoad() {
      await this.loadTree()
      let rows = this.$refs.dataView.rows
      let sp = new Map()
      rows.forEach(item => {
        let supplierId = item.supplierId
        sp.set(supplierId, item)
      })

      let supplierData =  this.treeData[0].children
      let supplier = []
      supplierData.forEach(item => {
        let flag = sp.get(item.id)
        if (flag) {
          supplier.push(item)
        }
      })
      this.treeData[0].children = supplier
    },
    searchResult() {
      let beginDate = new Date(this.query.beginDate).format(this.dates.defaultDatePattern)
      let endDate = new Date(this.query.endDate).format(this.dates.defaultDatePattern)
      if (beginDate > endDate) {
        this.utilMessage.error('起点时间不能大于终点时间')
        return
      }
      const param = {
        warehouseId: this.query.warehouseId,
        beginDate,
        endDate
      }
      this.$ajax.post('/dept/monthly_balance/save_monthly_balance', param).then(response => {
        if (response.success && this.utilMessage.success(response.msg)) {
          this.form = response.data
          let wrapper = this.getChildViewQueryWrapper()
          this.$refs.dataView.setQueryWrapper(wrapper)
          this.$refs.dv.setQueryWrapper(wrapper)
          this.activeName = 'specList'
          this.treeSetDataLoad()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .container {
    height: 100%;
    background-color: #fff;
  }
  .tree-container {
    padding:10px;
    margin-right:20px;
    border:solid 1px #DCDFE6;
    height:120%
  }
  .tree-filter {
    margin:10px;
    width:80%
  }
</style>
